﻿using NCrontab;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace myscheduler
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private void Form1_SizeChanged(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized)
            {
                this.Hide();
            }
            else
            {
                this.Show();
            }
        }

        private void notifyIcon1_Click(object sender, EventArgs e)
        {
            this.Show();
            this.WindowState = FormWindowState.Normal;
        }

        List<System.Threading.Timer> timerList = new List<System.Threading.Timer>();
        private void upateTimers()
        {
            foreach (var timer in timerList)
            {
                timer.Dispose();
            }
            timerList.Clear();
            List<Job> jobs = getJobList();
            foreach (Job job in jobs)
            {
                if (job.status == "on")
                {
                    var schedule = CrontabSchedule.Parse(job.cron);
                    DateTime now = DateTime.Now;
                    DateTime next = schedule.GetNextOccurrence(now);
                    var delay = next - now;
                    System.Threading.Timer timer = new System.Threading.Timer((_) =>
                    {
                        int pos = job.cmd.IndexOf(" ");
                        string cmd = job.cmd;
                        string arg = "";

                        if (pos > -1)
                        {
                            cmd = job.cmd.Substring(0, pos);
                            arg = job.cmd.Substring(pos + 1);
                        }
                        string workingDirectory = Path.GetDirectoryName(cmd);

                        ProcessStartInfo startInfo = new ProcessStartInfo
                        {
                            FileName = cmd,
                            Arguments = arg,
                            WindowStyle = ProcessWindowStyle.Normal,
                            CreateNoWindow = false,
                            WorkingDirectory = workingDirectory // 设置工作目录
                        };

                        try
                        {
                            using (Process process = Process.Start(startInfo))
                            {
                                Console.WriteLine("进程已启动，进程ID: " + process.Id);
                                process.WaitForExit();
                                Console.WriteLine("进程已退出，退出代码: " + process.ExitCode);
                            }
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine("启动进程时出现异常: " + ex.Message);
                        }

                    }, null, delay, TimeSpan.FromSeconds(60));
                    timerList.Add(timer);
                }

            }
        }

        private List<Job> getJobList()
        {
            var list = new List<Job>();
            string content = textBox1.Text;
            if (content.Trim().Length == 0)
            {
                return list;
            }

            string[] lines = textBox1.Lines;
            foreach (string line in lines)
            {
                string[] parts = line.Split(';');
                if (parts.Length != 3)
                {
                    continue;
                }

                string cron = parts[0];
                string cmd = parts[1];
                string status = parts[2];
                list.Add(new Job { cron = cron, cmd = cmd, status = status });
            }
            return list;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            try
            {
                textBox1.Text = Properties.Settings.Default.JobList;
                upateTimers();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            Properties.Settings.Default.JobList = textBox1.Text;
            Properties.Settings.Default.Save();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            upateTimers();
        }
    }

    public class Job
    {
        public string cmd { get; set; }
        public string cron { get; set; }
        public string status { get; set; }
    }
}
